// ------------------------ 获取分数，展示列表 -----------------
function renderScoreList() {
  axios.get("/score/list").then(({ data: { data, code } }) => {
    //   console.log(data);
    if (code === 0) {
      let arr = [];
      for (let key in data) {
        arr.push(`
                <tr>
                  <th scope="row">${key}</th>
                  <td>${data[key].name}</td>
                  <td class="score" data-batch="1" data-id="${key}">${data[key].score[0]}</td>
                  <td class="score" data-batch="2" data-id="${key}">${data[key].score[1]}</td>
                  <td class="score" data-batch="3" data-id="${key}">${data[key].score[2]}</td>
                  <td class="score" data-batch="4" data-id="${key}">${data[key].score[3]}</td>
                  <td class="score" data-batch="5" data-id="${key}">${data[key].score[4]}</td>
                </tr> `);
      }
      qs("tbody").innerHTML = arr.join("");
    }
  });
}
renderScoreList();
// ------------------------ 可编辑的表格 -----------------------
qs("tbody").addEventListener("click", function (e) {
  if (e.target.classList.contains("score")) {
    let td = e.target;
    if (td.querySelector("input")) return;
    let text = td.innerText;
    td.innerHTML = "";
    let input = document.createElement("input");
    input.value = text;
    td.appendChild(input);
    input.focus();
    let flag = false;
    input.addEventListener("keyup", function (e) {
      if (e.key === "Enter") {
        let score = this.value;
        if (isNaN(score) || score < 0 || score > 100) {
          return alert("请输入0-100之间的数字");
        }
        let stu_id = td.dataset.id;
        let batch = td.dataset.batch;
        // 发送请求, 修改或录入成绩
        axios.post("/score/entry", { score, stu_id, batch }).then((res) => {
          const { code } = res.data;
          if (code === 0) {
            isEditOk = true;
            td.innerHTML = score;
          }
        });
      }
    });
    input.addEventListener("blur", function () {
      if (!flag) td.innerHTML = text;
    });
  }
});
